/****************************************************************************
* Copyright (c) 2008, j. montgomery, ATGi                                   *
* All rights reserved.                                                      *
*                                                                           *
* Redistribution and use in source and binary forms, with or without        *
* modification, are permitted provided that the following conditions        *
* are met:                                                                  *
*                                                                           *
* - Redistributions of source code must retain the above copyright          *
*   notice, this list of conditions and the following disclaimer.           *
*                                                                           *
* - Redistributions in binary form must reproduce the above                 *
*   copyright notice, this list of conditions and the following             *
*   disclaimer in the documentation and/or other materials provided         *
*   with the distribution.                                                  *
*                                                                           *
* - Neither the name of ATGi nor the names of its contributors may          *
*   be used to endorse or promote products derived from this software       *
*   without specific prior written permission.                              *
*                                                                           *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS         *
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE            *
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,       *
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES                  *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR        *
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)        *
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,       *
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)             *
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED       *
* OF THE POSSIBILITY OF SUCH DAMAGE.                                        *
*****************************************************************************
*/
using System;
using System.Text.RegularExpressions;

namespace DnSmtp.Message
{
	/// <summary>
	/// Represents an Email Address field called a Target (http://cr.yp.to/immhf/addrlist.html).
	/// </summary>
	/// <remarks>
	/// A target is either
	/// 1. an encoded address or 
	/// 2. an optional phrase followed by a bracketed address (usually the Name associated with the email address).
	/// 
	/// Examples:
	///      "The Boss" <God@heaven.af.mil>
	///		 "Angels mailing list" <angels@heaven.af.mil>
	/// </remarks>
	public struct EmailAddress
	{
		// TODO: Look into compiling this RegEx into an assembly
		// http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html
		public static readonly string EMAIL_REGEX = @"^(<?(([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))>?)$";
		public static readonly string PHRASE_REGEX = @"^([a-zA-Z0-9()-_=+;:'|~?/{} ]{0,100})$";
		public static readonly string TARGET_REGEX = "^(\"([a-zA-Z0-9()-_,;:'|~/{} ]{0,100})\") (<?(([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?))>?)$";

		private string _emailAddress;	// _emailAddress address stores the bob@hotmail.com portion of an email address "Bob Saggett" <bob@hotmail.com>
		private string _name;			// _name address stores a phrase, e.g. The "Bob Saggett" portion of an email address "Bob Saggett" <bob@hotmail.com>
		private string _domainName;
		#region Properties
		public string Email
		{
			get 
			{
				return _emailAddress;
			}
			set 
			{
				ValidateAndSetAddress(value);
			}
		}

		public string Name 
		{
			get 
			{
				return _name;
			}
			set 
			{
				ValidateAndSetName(value);
			}
		}

		public string Domain
		{
			get
			{
				return _domainName;
			}
		}

		#endregion Properties

		#region Constructors
		public EmailAddress(string emailAddress) 
		{
			_name = string.Empty;
			_emailAddress = null;
			_domainName = null;
			ValidateAndSetAddress(emailAddress);
		}

		public EmailAddress(string emailAddress, string name) : this(emailAddress)
		{
			ValidateAndSetName(name);
		}
		#endregion Constructors

		// Code to parse Email address Target made up of a Phrase and a Bracketed Email address, e.g. "Bob Saggett" <bob@hotmail.com>
		public static EmailAddress Parse(string target) 
		{
			if(target == null)
				throw new ArgumentNullException("target");

			// TODO: Write code to parse the Phrase and bracketed email address and return a new EmailAddress
			if(Regex.IsMatch(target, TARGET_REGEX))
			{
				string[] split = Regex.Split(target, TARGET_REGEX);
				EmailAddress ea = new EmailAddress(split[4], split[2]);
				return ea;
			}
			else if(Regex.IsMatch(target, EMAIL_REGEX))
			{
				string[] split = Regex.Split(target, EMAIL_REGEX);
				EmailAddress ea = new EmailAddress(split[2]);
				return ea;
			}
			else 
			{
				throw new FormatException("Invalid email address.");
			}
		}

		public override string ToString()
		{
			// returns a Target (a Phrase + a bracketed address)
			if(_name == string.Empty) 
			{
				return "<" + _emailAddress + ">";
			}
			else 
			{
				return "\"" + _name + "\"" + " <" + _emailAddress + ">";
			}
		}

		private void ValidateAndSetName(string name)
		{
			if (Regex.IsMatch(name, PHRASE_REGEX))
			{
				_name = name;
			}
			else
			{
				throw new ApplicationException("There are invalid characters in the name field: '" + name + "'");
			}
		}

		private void ValidateAndSetAddress(string emailAddress)
		{
			if (Regex.IsMatch(emailAddress, EMAIL_REGEX))
			{
				_emailAddress = emailAddress;
				_domainName = _emailAddress.Substring(_emailAddress.IndexOf("@") + 1, _emailAddress.Length - (_emailAddress.IndexOf("@") + 1));
			}
			else
			{
				throw new ApplicationException("Email address '" + emailAddress + "' doesn't pass validation.");
			}
		}
	}
}
